package com.example.controller;

import com.example.common.Result;
import com.example.entity.*;
import com.example.service.*;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import org.springframework.web.bind.annotation.*;
import lombok.RequiredArgsConstructor;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 卡的订单的控制层
 **/
@RestController
@RequiredArgsConstructor
@RequestMapping("/cardOrder")
public class CardOrderController {

    private final CardOrderService cardOrderService;
    private final CardService cardService;
    private final UserService userService;
    private final CardUseService cardUseService;
    private final GridReservationService gridReservationService;

    /**
     * 增
     **/
    @PostMapping("/add")
    public Result add(@RequestBody CardOrder cardOrder) {
        Card card = cardService.selectById(cardOrder.getCardId());

        //初始化数据
        cardOrder.setTime(LocalDateTime.now());
        cardOrder.setStatus("待使用");
        cardOrder.setPrice(card.getPrice());
        cardOrder.setUserId(TokenUtils.getCurrentUser().getId());
        //卡的销量变多
        card.setNum(card.getNum() + 1);

        if(card.getValue()!=null&&card.getUnit()!=null){
            //卡的使用记录
            CardUse cardUse = new CardUse();

            User user = userService.selectById(cardOrder.getUserId());
            //给用户充值
            //如果是日卡或周卡，就自动兑换成值
            if (card.getUnit().equals("日")) {
                user.setCard(user.getCard() + 1);
                cardOrder.setStatus("已兑换");

                cardUse.setType("日卡自动转化为次数");
                cardUse.setCardId(card.getId());
                cardUseService.add(cardUse);
            } else if (card.getUnit().equals("周")) {
                user.setCard(user.getCard() + 7);
                cardOrder.setStatus("已兑换");

                cardUse.setType("周卡自动转化为次数");
                cardUse.setCardId(card.getId());
                cardUseService.add(cardUse);
            }
            userService.updateById(user);
        }else{
            cardOrder.setStatus("订单结束");
        }

        cardService.updateById(card);

        cardOrderService.add(cardOrder);
        return Result.success();
    }

    /**
     * 兑换
     **/
    /**
     * 兑换
     **/
    @GetMapping("/dh/{id}")
    public Result dh(@PathVariable Integer id) {
        CardOrder cardOrder = cardOrderService.selectById(id);
        Card card = cardService.selectById(cardOrder.getCardId());
        cardOrder.setStatus("已兑换");
        cardOrderService.updateById(cardOrder);

        User user = userService.selectById(TokenUtils.getCurrentUser().getId());

        int value = card.getValue();  // 比如 2
        String unit = card.getUnit(); // 比如 "月"
        int days = 0;

        switch (unit) {
            case "日":
                days = value;
                break;
            case "周":
                days = value * 7;
                break;
            case "月":
                days = value * 30;
                break;
            case "季":
                days = value * 90;
                break;
            case "年":
                days = value * 365;
                break;
            default:
                throw new IllegalArgumentException("未知单位: " + unit);
        }

        user.setCard(user.getCard() + days);

        CardUse cardUse = new CardUse();
        cardUse.setType("会员卡兑换次数");
        cardUse.setCardId(card.getId());
        cardUseService.add(cardUse);

        userService.updateById(user);
        return Result.success();
    }


    @Data
    public static class CardOrderDTO{
        private Integer cardOrderId;
        private Integer gridId;
        private LocalDate time;
    }

    /**
     * 使用会员卡或次数来锁定位置
     **/
    /**
     * 使用会员卡或次数来锁定位置
     **/
    @PostMapping("/use")
    public Result use(@RequestBody CardOrderDTO cardOrderDTO) {
        CardUse cardUse = new CardUse();
        GridReservation gridReservation = new GridReservation();

        // 使用次数
        if (cardOrderDTO.getCardOrderId() == 0) {
            User user = userService.selectById(TokenUtils.getCurrentUser().getId());
            if (user.getCard() < 1) {
                return Result.error("400", "次数不足,请去购买");
            }
            user.setCard(user.getCard() - 1);
            userService.updateById(user);

            cardUse.setType("消耗次数使用");

            gridReservation.setGridId(cardOrderDTO.getGridId());
            gridReservation.setTime(cardOrderDTO.getTime());
            gridReservation.setUserId(TokenUtils.getCurrentUser().getId());
            gridReservationService.add(gridReservation);
        } else {
            // 使用会员卡
            CardOrder cardOrder = cardOrderService.selectById(cardOrderDTO.getCardOrderId());
            Card card = cardService.selectById(cardOrder.getCardId());
            cardOrder.setStatus("已使用");
            cardOrderService.updateById(cardOrder);

            cardUse.setType("会员卡锁座位使用");
            cardUse.setCardId(card.getId());

            // 根据会员卡单位确定可用天数
            int days = 0;
            if ("月".equals(card.getUnit())) {
                days = card.getValue() * 30;
            } else if ("季".equals(card.getUnit())) {
                days = card.getValue() * 90;
            } else if ("年".equals(card.getUnit())) {
                days = card.getValue() * 365;
            }

            // 从今天开始，连续插入 days 条 GridReservation
            LocalDate startDate = LocalDate.now();
            for (int i = 0; i < days; i++) {
                GridReservation reservation = new GridReservation();
                reservation.setGridId(cardOrderDTO.getGridId());
                reservation.setUserId(TokenUtils.getCurrentUser().getId());
                reservation.setTime(startDate.plusDays(i));
                gridReservationService.add(reservation);
            }
        }

        cardUseService.add(cardUse);
        return Result.success();
    }


    /**
     * 删
     **/
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        cardOrderService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     **/
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        cardOrderService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 改
     **/
    @PutMapping("/update")
    public Result updateById(@RequestBody CardOrder cardOrder) {
        cardOrderService.updateById(cardOrder);
        return Result.success();
    }

    /**
     * 根据ID查询
     **/
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        CardOrder cardOrder = cardOrderService.selectById(id);
        return Result.success(cardOrder);
    }

    /**
     * 查询所有
     **/
    @GetMapping("/selectAll")
    public Result selectAll(CardOrder cardOrder) {
        List<CardOrder> list = cardOrderService.selectAll(cardOrder);
        return Result.success(list);
    }

    /**
     * 分页查询
     **/
    @GetMapping("/selectPage")
    public Result selectPage(CardOrder cardOrder,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<CardOrder> page = cardOrderService.selectPage(cardOrder, pageNum, pageSize);
        return Result.success(page);
    }

}